﻿
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Sykj.IServices;
using Sykj.Infrastructure;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Sykj.Components;
using Microsoft.Extensions.Logging;

namespace Sykj.Web.Areas.Manager.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Area("Manager")]
    public class LoginController : BaseController
    {
        IUsers _users;
        ILog _mslog;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="users"></param>
        /// <param name="mslog"></param>
        public LoginController(IUsers users, ILog mslog)
        {
            _users = users;
            _mslog = mslog;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> LogOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.Session.Clear();
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task<IActionResult> Login(string userName, string passWord)
        {
            var res = _users.ValidateLogin(userName, passWord);
            if (res.success)
            {
                Sykj.Entity.Users user = (Sykj.Entity.Users)res.data;
                if (user.UserType != "AA")
                {
                    return Json(Failed("非管理员不能登录系统！"));
                }

                //用户标识 SignIn
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, user.UserId.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, Newtonsoft.Json.JsonConvert.SerializeObject(_users.GetRoleList(user.UserId))));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

                //记录日志
                _mslog.Add(new Entity.Log
                {
                    IpAddress = HttpContext.Connection.LocalIpAddress.ToString(),
                    Title = "管理员登录",
                    Type = 2,
                    Url = Request.GetAbsoluteUri(),
                    UserId = user.UserId.ToString(),
                    Detail = "管理员登录",
                    UserName = user.UserName,
                    CreateDate = DateTime.Now
                });
            }
            return Json(res);
        }
    }
}